package org.ry.camera.activity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ry.camera.R;
import org.ry.camera.adapter.PhotoAdapter;
import org.ry.camera.adapter.PopupAdapter;
import org.ry.camera.app.CameraApplication;
import org.ry.camera.bean.PretendBean;
import org.ry.camera.tools.LogTool;
import org.ry.camera.tools.RegTool;
import org.ry.camera.tools.SharedSave;
import org.ry.camera.tools.Util;
import org.ry.camera.view.HackyViewPager;
import org.ry.camera.wxapi.WXEntryActivity;

import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.constant.WBConstants;
import com.tencent.mm.sdk.openapi.BaseReq;
import com.tencent.mm.sdk.openapi.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXImageObject;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXTextObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.SyncStateContract.Constants;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.GridView;
/**
 * 
 * @author renyang
 *
 */
public class PhotoActivity extends BaseActivity implements OnItemClickListener,OnPageChangeListener
,OnClickListener,IWeiboHandler.Response{

	private ListView mListView;
	private PopupWindow mPopupWindow;
	private View mPopupView;
	private HackyViewPager mHackyViewPager;
	private List<PretendBean> list;
	private TextView tvCurrentTotal;
	private PhotoAdapter mPhotoAdapter;
	private OnChangeDeleteStatusListener mOnChangeDeleteStatusListener;
	private OnItemClickListener mOnItemClickListener;
	private RelativeLayout llOperationBar;
	private ImageView ivDelete;
	private ImageView ivSelectAll;
	private int FLAG = 5;
	private GridView mGridView;
	private PopupAdapter mPopupAdapter;
	private int popupPosition = 0;
	private boolean isFirstAllSelect ;
	private ImageView ivBack;

	private IWeiboShareAPI  mWeiboShareAPI = null;
	//分享的图片
	private ImageView mShareImageView;
	private EditText mShareEditText;

	@Override
	protected void initListener() {
		// TODO Auto-generated method stub
		mListView.setOnItemClickListener(this);
		ivDelete.setOnClickListener(this);
		mGridView.setOnItemClickListener(this);
		ivSelectAll.setOnClickListener(this);
		ivBack.setOnClickListener(this);
	}

	@Override
	protected void initDate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_photo);

		mListView = (ListView)findViewById(R.id.photo_lv);
		llOperationBar = (RelativeLayout)findViewById(R.id.operation_bar);
		llOperationBar.setVisibility(View.GONE);
		ivDelete = (ImageView)findViewById(R.id.delete);	
		list =getPhoto(getStaticPath());	
		mGridView = (GridView)findViewById(R.id.photo_gv);
		ivSelectAll = (ImageView)findViewById(R.id.select_all);
		ivBack = (ImageView)findViewById(R.id.back);
		isFirstAllSelect = true;

		if(list != null && list.size() > 0){
			mPhotoAdapter = new PhotoAdapter(list, this,mGridView);
			mGridView.setAdapter(mPhotoAdapter);
		}

		mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, CameraApplication.SINA_APP_KEY);
		if (savedInstanceState != null) {
			mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
		}

	}

	private String getPath(){
		return SharedSave.get(PhotoActivity.this, CameraActivity.PHOTO_PATH);
	}

	private String getStaticPath(){

		String sPath = getPath();

		if(TextUtils.isEmpty(sPath)){
			return DEFULT_PATH;
		}

		return sPath;
	}

	private List<PretendBean> getPhoto(String path){

		List<PretendBean> list = null;

		if(!TextUtils.isEmpty(path)){

			File mFile = new File(path); 

			File[] fileList = mFile.listFiles();

			list = new ArrayList<PretendBean>();

			if(fileList == null){
				return list;
			}

			boolean isStartThread = false;

			int count = 0;

			for(File file : fileList){

				list.add(packagingBean(file.getName(), decodeFile(file)));

				if(++count >= LIMIT){
					isStartThread = true;
					break;
				}
			}

			if(isStartThread){
				startLoadThread(fileList, count);
			}
		}

		return list;

	}

	private void startLoadThread(final File[] fileList,final int startCount){

		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				int num = 0;

				for(File file : fileList){

					if(++num > startCount){
						list.add(packagingBean(file.getName(), decodeFile(file)));
					}
					mHandler.sendEmptyMessage(UPDATE_DATE);
				}

			}
		}).start();
	}

	private PretendBean packagingBean(String name,Bitmap bitmap){

		return new PretendBean(bitmap,name);
	}

	private Bitmap decodeFile(File f){
		Bitmap b = null;
		try {
			//Decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;

			FileInputStream fis = new FileInputStream(f);
			BitmapFactory.decodeStream(fis, null, o);
			fis.close();

			int sampleSize = computeSampleSize(o, -1, 480*480);
			/**
			 *  for the general case 2
			 */
			//LogTool.i("sampleSize:"+sampleSize);

			o.inSampleSize = sampleSize;

			o.inJustDecodeBounds = false;
			fis = new FileInputStream(f);
			b = BitmapFactory.decodeStream(fis, null, o);
			fis.close();
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return b;
	}

	private int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {  
		int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels); 
		//LogTool.i("initialSize:"+initialSize);
		int roundedSize;  
		if (initialSize <= 8) {  
			roundedSize = 1;  
			while (roundedSize < initialSize) {  
				roundedSize <<= 1;  
			}  
		} else {  
			roundedSize = (initialSize + 7) / 8 * 8;  
		}  
		return roundedSize;  
	}  

	private int computeInitialSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) {  
		double w = options.outWidth;  
		double h = options.outHeight;

		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));  
		int upperBound = (minSideLength == -1) ? 128 :(int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));  
		if (upperBound < lowerBound) {  
			// return the larger one when there is no overlapping zone.  
			return lowerBound;  
		}  
		if ((maxNumOfPixels == -1) && (minSideLength == -1)) {  
			return 1;  
		} else if (minSideLength == -1) {  
			return lowerBound;  
		} else {  
			return upperBound;  
		}  
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case android.R.id.home:
			//goBack();
			break;
		case R.id.setting :

			if(mOnChangeDeleteStatusListener != null){

				if(llOperationBar.getVisibility() == View.VISIBLE){
					llOperationBar.setVisibility(View.GONE);
					setGridView();
				}else{
					llOperationBar.setVisibility(View.VISIBLE);
					setListView();
				}
			}
			break;
		default:
			return super.onOptionsItemSelected(item);
		}
		return false;

	}

	private void setListView(){
		mGridView.setVisibility(View.GONE);
		mListView.setVisibility(View.VISIBLE);
		mPhotoAdapter.setView(mListView);
		mListView.setAdapter(mPhotoAdapter);
	}

	private void setGridView(){
		mGridView.setVisibility(View.VISIBLE);
		mListView.setVisibility(View.GONE);
		mPhotoAdapter.setView(mGridView);
		mGridView.setAdapter(mPhotoAdapter);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		if(mPhotoAdapter.getCurrentStatus()){

			mOnItemClickListener.onItemClick(position);
		}else{

			if(mPopupWindow == null){

				mPopupView = View.inflate(PhotoActivity.this,
						R.layout.item_popup_photo, null);

				mHackyViewPager = (HackyViewPager)mPopupView.findViewById(R.id.photoPager);

				mHackyViewPager.setOnPageChangeListener(this);

				mPopupWindow = new PopupWindow(mPopupView,
						LayoutParams.MATCH_PARENT,
						LayoutParams.MATCH_PARENT);

				mPopupWindow.setBackgroundDrawable(new ColorDrawable(
						Color.TRANSPARENT));

				tvCurrentTotal = (TextView)mPopupView.findViewById(R.id.tv_current_total);
				tvCurrentTotal.setText(position + 1 +"/" + list.size() );

				ImageView ivDelete = (ImageView)mPopupView.findViewById(R.id.iv_delete);
				ivDelete.setOnClickListener(this);

				ImageView ivSinaShare = (ImageView)mPopupView.findViewById(R.id.iv_sina_share);
				ivSinaShare.setOnClickListener(this);

				ImageView ivWeixinShare = (ImageView)mPopupView.findViewById(R.id.iv_weixin_share);
				ivWeixinShare.setOnClickListener(this);

				if(list != null && list.size() > 0){
					mPopupAdapter = new PopupAdapter(list);
					mHackyViewPager.setAdapter(mPopupAdapter);
				}

			}
			if(mPopupAdapter != null){
				mPopupAdapter.setUpdateList(list);
				mHackyViewPager.setCurrentItem(position);
				mPopupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
			}


		}
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageSelected(int position) {
		// TODO Auto-generated method stub
		tvCurrentTotal.setText(position + 1 +"/" + list.size() );
		popupPosition = position;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.photo_menu, menu);
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if(keyCode == KeyEvent.KEYCODE_BACK) {

			if(mPopupWindow != null && mPopupWindow.isShowing()){
				mPopupWindow.dismiss();
				mPhotoAdapter.notifyDataSetChanged();
				return true;
			}else{
				goBack();
			}
		}

		return super.onKeyDown(keyCode, event);
	}
	public interface OnChangeDeleteStatusListener{

		void onChangeDeleteStatus(boolean isListView);
	}

	public void setOnChangeDeleteStatusListener(OnChangeDeleteStatusListener mOnChangeDeleteStatusListener){
		this.mOnChangeDeleteStatusListener = mOnChangeDeleteStatusListener;
	}

	private void goBack(){
		isInitCamear = false;
		finish();
	}

	public interface OnItemClickListener{

		void onItemClick(int position);

		void onAllSelect();

		void onAllCancel();
	}

	public void setOnItemClickListener(OnItemClickListener mOnItemClickListener){
		this.mOnItemClickListener = mOnItemClickListener;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.delete:
			titleDelete(false);
			break;
		case R.id.iv_delete:
			titleDelete(true);
			break;
		case R.id.select_all:
			if(isFirstAllSelect){
				mOnItemClickListener.onAllSelect();
				isFirstAllSelect = false;
				ivSelectAll.setBackgroundResource(R.drawable.btn_check_on_holo_light);
			}else{
				mOnItemClickListener.onAllCancel();
				isFirstAllSelect = true;
				ivSelectAll.setBackgroundResource(R.drawable.btn_check_off_holo_light);
			}
			break;
		case R.id.back:
			goBack();
			break;
		case R.id.iv_sina_share:

			shareDialog(Share.Sina);
			break;
		case R.id.iv_weixin_share:
			
			SharedSave.saveBitmap(PhotoActivity.this, list.get(popupPosition).getmPic(), 
					CameraApplication.CACHE_BITMAP);
			
			Intent mIntent = new Intent(PhotoActivity.this,WXEntryActivity.class);
			startActivity(mIntent);
			break;
		}
	}

	enum Share{
		Sina,WinXin;
	}

	private void shareDialog(final Share mEnum){
		AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(PhotoActivity.this);
		View contentView = LayoutInflater.from(PhotoActivity.this).inflate(R.layout.popup_share,null);
		mAlertDialog.setView(contentView);
		mAlertDialog.setPositiveButton(getString(R.string.share), new AlertDialog.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				switch (mEnum) {
				case Sina:
					mWeiboShareAPI.registerApp();
					sendMessage();
					break;
				case WinXin:
					
					break;
				}

			}
		});
		mAlertDialog.setNegativeButton(getString(R.string.cancel), null);
		mShareImageView = (ImageView)contentView.findViewById(R.id.share_iv);
		mShareEditText = (EditText)contentView.findViewById(R.id.share_et);
		mShareImageView.setImageBitmap(list.get(popupPosition).getmPic());
		mAlertDialog.show();
	}

	private void titleDelete(final boolean isSimple){
		AlertDialog.Builder builder = new Builder(PhotoActivity.this);
		builder.setMessage(getResources().getString(R.string.delete_msg));
		builder.setPositiveButton(getResources().getString(R.string.okey),new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				ivSelectAll.setBackgroundResource(R.drawable.btn_check_off_holo_light);
				if(isSimple){
					simpleDelete();
				}else{
					delete();
				}

			}
		});
		builder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			}
		});
		builder.create().show();
	}

	private void simpleDelete(){
		deleteImage(popupPosition);
		clearList();

		if(list.size() == 0){
			mPopupWindow.dismiss();
			mPhotoAdapter.setList(list);
			mPhotoAdapter.notifyDataSetChanged();
			return;
		}

		mPhotoAdapter.setList(list);
		mPopupAdapter.setUpdateList(list);
		mHackyViewPager.setAdapter(mPopupAdapter);
		mPopupAdapter.notifyDataSetChanged();

		int curPosition = 0;

		if(popupPosition < list.size()){
			curPosition = popupPosition + 1;
		}else{
			curPosition = popupPosition;
		}
		tvCurrentTotal.setText(curPosition +"/" + list.size() );
		popupPosition = curPosition - 1;
		mHackyViewPager.setCurrentItem(popupPosition);
	}

	private void delete(){
		String mSeleted = mPhotoAdapter.getDateMap();
		int length = mSeleted.length();
		int start = 1;
		int end = 5;
		FLAG = 5;
		while(length >=end){
			String str = mSeleted.substring(start, end);
			while(RegTool.isContainNumber(str)){
				start++;
				end++;
				FLAG++;
				str = mSeleted.substring(start, end);
			}
			if(str.equals(PhotoAdapter.CHECKED)){
				String value = mSeleted.substring(start - (FLAG-4), start);
				int position = Integer.parseInt(value);
				deleteImage(position);
			}
			FLAG = 5;
			start = start+FLAG;
			end = end+FLAG;
		}
		clearList();
		mPhotoAdapter.setDateMap("");
		mPhotoAdapter.setList(list);
		mPhotoAdapter.notifyDataSetChanged();
	}

	private void deleteImage(int position){
		String name = list.get(position).getmName();
		String myPath = getStaticPath()+"/"+name;
		File mFile = new File(myPath);

		if(mFile.exists()){
			if(mFile.delete()){
				list.set(position, null);
			}

		}
	}

	private void clearList(){

		List<PretendBean> listTemp = new ArrayList<PretendBean>();

		for(PretendBean mPretendBean : list){

			if(mPretendBean == null){
				continue;
			}
			listTemp.add(mPretendBean);
		}
		list = listTemp;

	}

	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);

			switch (msg.what) {
			case UPDATE_DATE:
				mPhotoAdapter.notifyDataSetChanged();
				if(mPopupAdapter != null){
					mPopupAdapter.notifyDataSetChanged();
				}
				break;
			}
		}

	};

	@Override
	public void onResponse(BaseResponse baseResp) {
		// TODO Auto-generated method stub
		switch (baseResp.errCode) {
		case WBConstants.ErrorCode.ERR_OK:
			Toast.makeText(this, R.string.weibosdk_demo_toast_share_success, Toast.LENGTH_LONG).show();
			break;
		case WBConstants.ErrorCode.ERR_CANCEL:
			Toast.makeText(this, R.string.weibosdk_demo_toast_share_canceled, Toast.LENGTH_LONG).show();
			break;
		case WBConstants.ErrorCode.ERR_FAIL:
			Toast.makeText(this, 
					getString(R.string.weibosdk_demo_toast_share_failed) + "Error Message: " + baseResp.errMsg, 
					Toast.LENGTH_LONG).show();
			break;
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		mWeiboShareAPI.handleWeiboResponse(intent, this);
		
	}

	private void sendMessage() {

		if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
			int supportApi = mWeiboShareAPI.getWeiboAppSupportAPI();
			if (supportApi >= 10351) {
				sendMultiMessage();
			} else {
				sendSingleMessage();
			}
		}
	}

	private void sendMultiMessage() {

		WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
		weiboMessage.textObject = getTextObj();
		weiboMessage.imageObject = getImageObj();
		SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
		request.transaction = String.valueOf(System.currentTimeMillis());
		request.multiMessage = weiboMessage;
		mWeiboShareAPI.sendRequest(request);
	}

	private TextObject getTextObj() {
		TextObject textObject = new TextObject();
		textObject.text = getSharedText();
		return textObject;
	}
	

	private ImageObject getImageObj() {
		ImageObject imageObject = new ImageObject();
		BitmapDrawable bitmapDrawable = (BitmapDrawable) mShareImageView.getDrawable();
		imageObject.setImageObject(bitmapDrawable.getBitmap());
		return imageObject;
	}

	private String getSharedText() {
		String str = mShareEditText.getText().toString();
		if(TextUtils.isEmpty(str)){
			return " ";
		}else{
			return str;
		}
	}

	private void sendSingleMessage() {

		WeiboMessage weiboMessage = new WeiboMessage();
		weiboMessage.mediaObject = getTextObj();
		weiboMessage.mediaObject = getImageObj();
		SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
		request.transaction = String.valueOf(System.currentTimeMillis());
		request.message = weiboMessage;
		mWeiboShareAPI.sendRequest(request);
	}
}
